package com.example.demo.controller;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.common.Result;
import com.example.demo.entity.Rules2;
import com.example.demo.entity.User;
import com.example.demo.mapper.Rules2Mapper;

import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/rules2")
@CrossOrigin
public class RulesController {
    @Resource
    Rules2Mapper rules2Mapper;

    @PostMapping
    public Result<?> save(@RequestBody Rules2 rules2){
//        Rules2Mapper rules2Mapper;

//        String jsonRule = JSON.toJSONString(rules2.getRule());
//        rules2.setRule(jsonRule);

        rules2Mapper.insertWithJson(rules2);
        return Result.success();
    }
    @PutMapping
    public Result<?> update(@RequestBody Rules2 rules2){
//        String jsonRule = JSON.toJSONString(rules2.getRule());
//        rules2.setRule(jsonRule);
        rules2Mapper.insertWithJson(rules2);
        return Result.success();
    }

    @DeleteMapping("/{id}")
    public Result<?> delete(@PathVariable Long id) {
        rules2Mapper.deleteById(id);
        return Result.success();
    }
    @GetMapping("/{id}")
    public Result<?> getById(@PathVariable Long id) {
        return Result.success(rules2Mapper.selectById(id));
    }
    @GetMapping
    public Result<?> findPage(@RequestParam(defaultValue = "1") Integer pageNum,
                              @RequestParam(defaultValue = "10") Integer pageSize,
                              @RequestParam(defaultValue = "") String search
                              ){
        LambdaQueryWrapper<Rules2> wrapper = Wrappers.<Rules2>lambdaQuery();

        if (StrUtil.isNotBlank(search)) {
            wrapper.like(Rules2::getYear, search);
        }

        Page<Rules2> RulePage=rules2Mapper.selectPage(new Page<>(pageNum,pageSize),wrapper);
        return Result.success(RulePage);
    }
}

